/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import java.util.Collection;

import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.convert.ConversionService;
import com.tengtong.duang.commons.utils.ClassUtils;

/**
 * Collection 转  String
 *
 * @author jai
 * @since: v1.0
 */
public class CollectionToStringConverter implements ConditionalConverter{

	/**
	 * 内定分隔符为 ","
	 */
	private static final String DELIMITER = ",";
	
	private final ConversionService helperConverter;
	
	private String delimiter = DELIMITER;
	
	public CollectionToStringConverter(ConversionService helperConverter){
		this.helperConverter = helperConverter;
	}
	
	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@Override
	public Object convert(Object source, Class targetType) {
		if (source == null) {
			return null;
		}
		Collection<?> sourceCollection = (Collection<?>) source;
		if(sourceCollection.size() == 0){
			return "";
		}
		
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (Object sourceElement : sourceCollection) {
			if(i > 0){
				sb.append(delimiter);
			}
			Object targetElement = this.helperConverter.convert(sourceElement, targetType);
			sb.append(targetElement);
			i++;
		}
		return sb.toString();
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		return ClassUtils.isInheritance(sourceType, Collection.class) && String.class.equals(targetType);
	}
	
	/**
	 * 设置分隔符
	 * 
	 * @param delimiter
	 */
	public void setDelimiter(String delimiter){
		this.delimiter = delimiter;
	}
}
